<template>
  <div class="calling-screen">
    <!-- 顶部标题区 -->
    <div class="screen-header">
      <h1 class="main-title">请凭取餐码取餐</h1>
      <div class="refresh-area">
        <!-- 手动刷新新提示动画 -->
        <div class="new-orders-indicator" v-if="hasNewOrders">
          <span class="pulse-dot"></span>
          <span>有新订单</span>
        </div>

        <!-- 手动刷新按钮 -->
        <el-button
            icon="Refresh"
            type="primary"
            circle
            size="small"
            @click="fetchPendingOrders"
            class="refresh-btn"
            :loading="isLoading"
        ></el-button>

        <!-- 自动刷新状态提示 -->
        <span class="auto-refresh-tip">
          自动刷新中（{{ refreshInterval / 1000 }}秒/次）
        </span>
      </div>
    </div>

    <!-- 核心取餐码展示区 -->
    <div class="code-container">
      <!-- 无待取餐订单时显示空状态 -->
      <div class="empty-state" v-if="pendingOrders.length === 0 && !isLoading">
        <el-empty
            description="暂无待取餐订单"
            image-size="120"
        ></el-empty>
      </div>

      <!-- 加载状态 -->
      <div class="loading-state" v-if="isLoading">
        <el-loading-spinner size="60" />
        <p>加载中...</p>
      </div>

      <!-- 待取餐订单取餐码网格 -->
      <div class="code-grid" v-else-if="pendingOrders.length > 0">
        <div
            class="code-card"
            v-for="order in pendingOrders"
            :key="order.id"
            :class="{
              'highlight-card': order.isNew,
              'urgent-card': order.isUrgent
            }"
            @click="markAsNotified(order.id)"
        >
          <!-- 新生成的取餐码高亮标记 -->
          <div class="new-tag" v-if="order.isNew">新</div>

          <!-- 加急标记 -->
          <div class="urgent-tag" v-if="order.isUrgent">加急</div>

          <!-- 取餐码大字体展示 -->
          <div class="pickup-code">{{ order.pickupCode }}</div>

          <!-- 订单辅助信息 -->
          <div class="order-info">
            订单{{ order.id }} | {{ formatTime(order.orderTime) }}
          </div>

          <!-- 餐品信息 -->
          <div class="order-items">
            {{ order.items }}
          </div>
        </div>
      </div>
    </div>

    <!-- 底部状态统计区 -->
    <div class="screen-footer">
      <div class="stat-item">
        <span class="stat-label">当前待取餐：</span>
        <span class="stat-value">{{ pendingOrders.length }} 单</span>
      </div>
<!--      <div class="stat-item">-->
<!--        <span class="stat-label">今日已完成：</span>-->
<!--        <span class="stat-value">{{ completedOrdersToday }} 单</span>-->
<!--      </div>-->
      <div class="stat-item">
        <span class="stat-label">最后刷新：</span>
        <span class="stat-value">{{ lastRefreshTime }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import http from '@/axios/http';
import { ElEmpty, ElButton, ElLoading } from 'element-plus';
import 'element-plus/es/components/empty/style/css';
import 'element-plus/es/components/button/style/css';
import 'element-plus/es/components/loading/style/css';

// 页面核心数据
const pendingOrders = ref([]); // 待取餐订单列表
const refreshInterval = ref(5000); // 自动刷新间隔（5秒）
const intervalId = ref(null); // 定时器ID
const lastRefreshTime = ref(''); // 最后刷新时间
const prevOrderIds = ref(new Set()); // 上一次的订单ID集合
const isLoading = ref(false); // 加载状态
const hasNewOrders = ref(false); // 是否有新订单
const completedOrdersToday = ref(0); // 今日已完成订单数

/**
 * 格式化时间：只显示时分，适配大屏简洁需求
 */
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  return new Date(timeStr).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

/**
 * 标记新订单和加急订单
 */
const markSpecialOrders = (newOrders) => {
  const newOrderIds = new Set(newOrders.map(order => order.id));
  const now = new Date();

  // 标记新订单和判断是否加急（下单超过15分钟）
  return newOrders.map(order => {
    const orderTime = new Date(order.orderTime);
    const isUrgent = (now - orderTime) > 15 * 60 * 1000; // 15分钟
    const isNew = !prevOrderIds.value.has(order.id);

    return {
      ...order,
      isNew,
      isUrgent,
      // 格式化餐品信息，只显示前两个
      items: order.items ?
          order.items.length > 2
              ? `${order.items.slice(0, 2).join('、')} 等${order.items.length}件`
              : order.items.join('、')
          : ''
    };
  });
};

/**
 * 从后端获取待取餐订单
 */
const fetchPendingOrders = async () => {
  isLoading.value = true;
  try {
    const res = await http.get('/glsb/get_pending_pickup_orders');
    if (res.data.result === 'success') {
      const newOrders = res.data.data || [];
      const markedOrders = markSpecialOrders(newOrders);

      // 检查是否有新订单
      hasNewOrders.value = markedOrders.some(order => order.isNew);

      pendingOrders.value = markedOrders;
      prevOrderIds.value = new Set(newOrders.map(order => order.id));
      lastRefreshTime.value = new Date().toLocaleTimeString();

      // 更新今日完成订单数
      completedOrdersToday.value = res.data.completedToday || 0;

      // 有新订单时播放提示音
      if (hasNewOrders.value) {
        playNotificationSound();
      }
    }
  } catch (error) {
    console.error('获取待取餐订单失败：', error);
  } finally {
    isLoading.value = false;
    // 5秒后自动清除新订单标记
    setTimeout(() => {
      pendingOrders.value = pendingOrders.value.map(order => ({
        ...order,
        isNew: false
      }));
      hasNewOrders.value = false;
    }, 5000);
  }
};

/**
 * 播放新订单提示音
 */
const playNotificationSound = () => {
  try {
    // 使用HTML5 Audio播放提示音
    const audio = new Audio('/sounds/notification.mp3'); // 假设项目中有这个音频文件
    audio.volume = 0.5;
    audio.play().catch(e => console.log('提示音播放失败:', e));
  } catch (e) {
    console.error('播放提示音出错:', e);
  }
};

/**
 * 手动标记订单为已通知（点击卡片时）
 */
const markAsNotified = (orderId) => {
  pendingOrders.value = pendingOrders.value.map(order =>
      order.id === orderId ? { ...order, isNew: false } : order
  );
  hasNewOrders.value = pendingOrders.value.some(order => order.isNew);
};

/**
 * 初始化自动刷新
 */
onMounted(() => {
  // 首次加载立即获取数据
  fetchPendingOrders();
  // 启动自动刷新定时器
  intervalId.value = setInterval(fetchPendingOrders, refreshInterval.value);
});

/**
 * 清理定时器
 */
onUnmounted(() => {
  if (intervalId.value) {
    clearInterval(intervalId.value);
  }
});

/**
 * 监听新订单，在开发环境可以添加桌面通知
 */
watch(hasNewOrders, (newVal) => {
  if (newVal && process.env.NODE_ENV === 'development' && 'Notification' in window) {
    if (Notification.permission === 'granted') {
      new Notification('新订单提醒', { body: '有新的待取餐订单' });
    } else if (Notification.permission !== 'denied') {
      Notification.requestPermission();
    }
  }
});
</script>

<style scoped>
/* 页面整体样式 */
.calling-screen {
  width: 100vw;
  height: 100vh;
  background-color: #121212;
  color: #ffffff;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 顶部标题区 */
.screen-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.main-title {
  font-size: 48px;
  font-weight: bold;
  color: #ff6700;
  margin: 0;
  letter-spacing: 2px;
  text-shadow: 0 2px 10px rgba(255, 103, 0, 0.3);
}

.refresh-area {
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 新订单指示器 */
.new-orders-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #4cd964;
  font-weight: 500;
  animation: fadeIn 0.5s;
}

.pulse-dot {
  width: 8px;
  height: 8px;
  background-color: #4cd964;
  border-radius: 50%;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(76, 217, 100, 0.7); }
  70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(76, 217, 100, 0); }
  100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(76, 217, 100, 0); }
}

.refresh-btn {
  background-color: #ff6700;
  border-color: #ff6700;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  background-color: #e05a00;
  border-color: #e05a00;
  transform: rotate(90deg);
}

.auto-refresh-tip {
  font-size: 14px;
  color: #aaaaaa;
}

/* 核心取餐码展示区 */
.code-container {
  flex-grow: 1;
  margin: 20px 0;
  overflow-y: auto;
  padding: 10px;
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 103, 0, 0.5) transparent;
}

.code-container::-webkit-scrollbar {
  width: 6px;
}

.code-container::-webkit-scrollbar-thumb {
  background-color: rgba(255, 103, 0, 0.5);
  border-radius: 3px;
}

.empty-state {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 加载状态 */
.loading-state {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20px;
  color: #ff6700;
}

/* 取餐码网格 */
.code-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 30px;
  width: 100%;
  max-width: 1600px;
  margin: 0 auto;
}

/* 取餐码卡片 */
.code-card {
  background-color: #ff6700;
  border-radius: 16px;
  padding: 25px 15px;
  text-align: center;
  position: relative;
  box-shadow: 0 4px 15px rgba(255, 103, 0, 0.3);
  transition: all 0.3s ease;
  cursor: pointer;
  overflow: hidden;
}

/* 卡片悬停效果 */
.code-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(255, 103, 0, 0.4);
}

/* 新订单卡片高亮 */
.highlight-card {
  animation: highlightPulse 2s infinite;
}

@keyframes highlightPulse {
  0% { box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.4); }
  70% { box-shadow: 0 0 0 15px rgba(255, 255, 255, 0); }
  100% { box-shadow: 0 0 0 0 rgba(255, 255, 255, 0); }
}

/* 加急订单样式 */
.urgent-card {
  background-color: #ff3b30;
  box-shadow: 0 4px 15px rgba(255, 59, 48, 0.4);
}

.urgent-card:hover {
  box-shadow: 0 8px 25px rgba(255, 59, 48, 0.6);
}

/* 标签样式 */
.new-tag, .urgent-tag {
  position: absolute;
  top: 10px;
  font-size: 14px;
  font-weight: bold;
  padding: 2px 8px;
  border-radius: 12px;
}

.new-tag {
  right: 10px;
  background-color: #ffffff;
  color: #ff6700;
}

.urgent-tag {
  left: 10px;
  background-color: #ffffff;
  color: #ff3b30;
  animation: urgentFlash 1.5s infinite;
}

@keyframes urgentFlash {
  0% { opacity: 1; }
  50% { opacity: 0.6; }
  100% { opacity: 1; }
}

/* 取餐码字体 */
.pickup-code {
  font-size: 45px;
  font-weight: 900;
  color: #ffffff;
  margin: 8px 0;
  letter-spacing: 5px;
  text-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
}

/* 订单辅助信息 */
.order-info {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 10px;
  padding-bottom: 8px;
  border-bottom: 1px dashed rgba(255, 255, 255, 0.3);
}

/* 餐品信息 */
.order-items {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin-top: 10px;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 底部统计区 */
.screen-footer {
  display: flex;
  justify-content: center;
  gap: 60px;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  margin-top: 20px;
  flex-wrap: wrap;
}

.stat-item {
  font-size: 18px;
  display: flex;
  align-items: center;
}

.stat-label {
  color: #aaaaaa;
  margin-right: 5px;
}

.stat-value {
  font-weight: bold;
  color: #ff6700;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .code-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  }

  .screen-footer {
    gap: 40px;
  }
}

@media (max-width: 768px) {
  .main-title {
    font-size: 32px;
  }

  .code-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 20px;
  }

  .pickup-code {
    font-size: 56px;
  }

  .screen-footer {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }

  .stat-item {
    justify-content: center;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* 加载动画增强 */
:deep(.el-loading-spinner) {
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
